package com.ck.hxc.controller;

import cn.idev.excel.FastExcel;
import com.ck.hxc.entity.User;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author hxc
 * @since 2025/2/7 17:34
 */
@RestController
@RequestMapping("/fastExcel")
public class TestFastExcelDownload {

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode("test", StandardCharsets.UTF_8);
    response.setHeader("Content-disposition",
                        "attachment;filename*=utf-8''" + fileName + ".xlsx");
    // 写入数据
    FastExcel.write(response.getOutputStream(), User.class)
    .sheet("模板")
    .doWrite(buildData());
    }

// 创建测试数据
    private List<User> buildData() {
        User user1 = new User();
        user1.setId(1);
        user1.setName("张三");
        user1.setAge(18);
        User user2 = new User();
        user2.setId(2);
        user2.setName("李四");
        user2.setAge(19);
        return List.of(user1, user2);
    }
}
